<template>
  <div>
    <div class="box box-fatal padding hover-shadow margin-bottom">
      <div class="box-header">
        <span>已选中用户</span>
        <span v-if="limit !== undefined">（限定 {{ limit }} 人）：</span>
        <a @click="cleanup" class="pull-right"><i class="fa fa-fw fa-remove"></i>清除已选</a>
        <div class="clearfix"></div>
      </div>
      <div class="box-body sea-gap-group">
        <transition name="el-zoom-in-right">
          <div v-if="props.modelValue.length === 0" class="text-warning">还未选中用户！</div>
        </transition>
        <el-tag v-for="(item, idx) in props.modelValue" :key="idx"
                @close="remove(item)" closable>{{ item.userName }}
        </el-tag>
      </div>
    </div>

    <span class="text-secondary">{{ tips }}</span>
    <div class="box padding hover-shadow">
      <el-table :data="list" @cell-click="rowClick">
        <el-table-column property="deptName" label="部门"></el-table-column>
        <el-table-column property="userName" label="用户"></el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup>

import {ref} from "vue";

/**
 * 用户选择面板
 */
const props = defineProps({
    // 默认值，注意 value 是单向输入，需要通过 change 事件侦听变化
    modelValue: {type: Array, default: undefined}
    // 操作成功
    , limit: {type: [Number, String], default: undefined}
    // 一些操作提示
    , tips: {type: String, default: '点击下列表格选中用户！'}
});


// Emits
const emit = defineEmits(['update:modelValue', 'change']);

const list = ref([
    {id: 'A', deptName: '部门A', userName: '用户A'}
    , {id: 'B', deptName: '部门B', userName: '用户B'}
]);

let value = [];

/**
 * 行点击事件
 * @param row -
 */
const rowClick = (row) => {
    if (props.limit === 1) {
        value[0] = row;
        onChange();
    } else {
        const arr = value;
        if (props.limit === undefined || value.length < props.limit) {
            for (let i = 0; i < arr.length; i++) {
                if (arr[i].id === row.id) {
                    return;
                }
            }
            value.push(row);
            onChange();
        } else {
            Layers.warn('只需要选中 ' + props.limit + ' 个人！');
        }
    }
}
/**
 * 移除一个用户
 * @param row -
 */
const remove = (row) => {
    const arr = value;
    for (let i = 0; i < arr.length; i++) {
        if (arr[i].id === row.id) {
            value.splice(i, 1);
            onChange();
            break;
        }
    }
}

/**
 * 清除所有用户
 */
const cleanup = () => {
    value.splice(0, value.length);
    onChange();
}

/**
 * 数据发生变化
 */
const onChange = () => {
    let ret = props.limit === 1 ? value[0] : value.slice(0);
    emit('update:modelValue', ret);
    emit('change', ret);
}
</script>

<style scoped>
</style>